import React, { useState, useRef, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import { ProCard, ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import { Button, Space, Table, Tag } from 'antd';
import type { Key } from 'antd/lib/table/interface';
import moment from 'moment'; // 导入moment库，用于对时间进行格式化
import { PageContainer } from '@ant-design/pro-layout';
import { connect, useDispatch } from 'umi';
import { getNoticeReadAll } from '@/services/noticeforstu';
const statusMap = {
  1: {
    color: 'green',
    text: '已读',
  },
  0: {
    color: 'red',
    text: '未读',
  },
};
export type status = {
  color: string;
  text: string;
};
export type TableListItem = {
  key: number;
  id: number;
  originatorName: string;
  status: number;
  title: string;
  createTime: string;
};

const columns: ProColumns<TableListItem>[] = [
  {
    title: <b>发起人</b>,
    width: 120,
    dataIndex: 'originatorName',
  },
  {
    title: <b>状态</b>,
    width: 120,
    dataIndex: 'status',
    valueType: 'select', // 指定valueType为'select'
    valueEnum: {
      1: {
        text: '已读',
        status: 'Success',
      },
      0: {
        text: '未读',
        status: 'Error',
      },
    },
    // 1. 添加filters属性用于配置筛选选项
    filters: [
      { text: '已读', value: 1 },
      { text: '未读', value: 0 },
    ],
    // 2. 添加onFilter属性用于指定筛选处理函数
    onFilter: (value, record) => record.status === value,
    filterMultiple: false,
    render: (_, record) => (
      <Tag color={statusMap[record.status].color}>{statusMap[record.status].text}</Tag>
    ),
  },
  {
    title: <b>通知主题</b>,
    width: 1200,
    align: 'left',
    dataIndex: 'title',
    render: (text) => <b style={{ fontWeight: 'bold' }}>{text}</b>,
  },
  {
    title: <b>创建时间</b>,
    width: 140,
    key: 'since',
    dataIndex: 'createTime',
    valueType: 'dateTime', // 设置valueType为'dateTime'，用于格式化时间戳
    sorter: (a, b) => moment(a.createTime).unix() - moment(b.createTime).unix(), // 按时间戳排序
    sortDirections: ['descend', 'ascend'], // 设置排序方向
    showSorterTooltip: true, // 隐藏默认提示语
  },
];

const TableList: React.FC = () => {
  // 创建表格数据源的状态变量tableListData
  const [tableListData, setTableListData] = useState<TableListItem[]>();
  // 创建状态变量unreadKeys，用于存储未读行的key
  const [unreadKeys, setUnreadKeys] = useState<number[]>([]);
  // 创建状态变量，用于存储用户选择的行的keys
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
  const dispatch = useDispatch();
  const history = useHistory();
  useEffect(() => {
    //获取数据接口
    dispatch({
      type: 'Model_noticeforstuModel/getNoticeListEffects',
      payload: {
        // code: JSON.parse(props.user.currrentuser).account,
        code: localStorage.getItem('userAccount'),
        callback: (value: any) => {
          // console.log(value);
          setTableListData(value);
        },
      },
    });
  }, []);

  //点击“全部标记为已读”按钮后的事件处理函数
  const handleMarkAllAsRead = () => {
    if (tableListData) {
      const allReadKeys = tableListData
        .filter((item) => item.status === 0) // 这里使用数字值来判断状态
        .map((item) => item.key);
      setUnreadKeys(allReadKeys);
      // 修改数据源中所有未读行的状态为"已读"
      const updatedData = tableListData.map(
        (item) => (allReadKeys.includes(item.key) ? { ...item, status: 1 } : item), // 将状态改为1表示"已读"
      );
      // 更新表格数据源状态
      setTableListData(updatedData);
      getNoticeReadAll('', localStorage.getItem('userAccount'));
    }
  };

  // 点击未读信息，转换为已读
  const handleRowClick = (record: TableListItem) => {
    if (tableListData) {
      // 判断当前点击的行是否是未读
      if (record.status === 0) {
        const updatedData = tableListData.map(
          (item) => (item.key === record.key ? { ...item, status: 1 } : item), // 将状态改为1表示"已读"
        );
        setTableListData(updatedData);
      }
      // 获取通知的id和学生code
      const notificationId = record.id;
      const studentCode = localStorage.getItem('userAccount'); // 替换为学生的code

      // 跳转到NotificationDetail组件并传递参数
      history.push(`/notification/list/detail?id=${notificationId}&stuCode=${studentCode}`);
    }
  };

  return (
    <PageContainer>
      <ProCard>
        <ProTable<TableListItem>
          columns={columns}
          //配置表格的行选择功能。
          rowSelection={{
            selectedRowKeys, // 设置用户选择的行
            onChange: (keys) => setSelectedRowKeys(keys), // 更新用户选择的行
            selections: [
              Table.SELECTION_ALL, //全选
              Table.SELECTION_INVERT, //反选
              Table.SELECTION_NONE, //全不选
            ],
          }}
          dataSource={tableListData}
          options={false}
          search={false}
          pagination={{
            //分页
            pageSize: 10,
          }}
          rowKey="key"
          headerTitle="批量操作"
          toolBarRender={() => [
            <Button key="show" onClick={handleMarkAllAsRead}>
              全部标记为已读
            </Button>,
          ]}
          // 6. 添加onRow属性用于设置点击事件处理函数
          onRow={(record) => ({
            onClick: () => handleRowClick(record),
          })}
        />
      </ProCard>
    </PageContainer>
  );
};

export default connect(({ Model_noticeforstuModel }: any) => ({
  Model_noticeforstuModel,
}))(TableList);
